package com.yuan.pay_mall.controller;

import com.yuan.pay_mall.form.UserLoginForm;
import com.yuan.pay_mall.form.UserRegisterForm;
import com.yuan.pay_mall.pojo.User;
import com.yuan.pay_mall.service.IUserService;
import com.yuan.pay_mall.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import static com.yuan.pay_mall.consts.MallConst.CURRENT_USER;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
/*  @Valid注解：用于校验，对于前端传进来的参数进行判断检查。其使用方法如下：
    在自定义的类中的字段上（参数字段），加上校验条件注解@NotNull
* */

    @PostMapping ("/user/register")
  //  public void register(@RequestBody String username){
//    public ResponseVo register(@RequestBody User user){
    public ResponseVo register(@Valid @RequestBody UserRegisterForm userRegisterForm
                               /**
                                * {@link Valid:与BindingResult绑定配合使用，不然会导致参数校验不成功}
                                */
                          //     BindingResult bindingResult
    ){
        //1.先判断内容是否为空
        //2.密码，邮箱是否都为空
       /* if(bindingResult.hasErrors()){
            log.error("注册提交的信息有误！{}{}",
                    bindingResult.getFieldError().getField(),
                    bindingResult.getFieldError().getDefaultMessage());
            return ResponseVo.error(PASSWORD_ERROR,bindingResult);*/

                  //  ,bindingResult.getFieldError().getField()+""+bindingResult.getFieldError().getDefaultMessage());
       // }
//        log.info("username={}", user.getUsername());
        //return ResponseVo.success();
       // return ResponseVo.error(ResponseEnum.NEED_LOGIN);
      //  return ResponseVo.error(NEED_LOGIN);//直接引包进来，更加简洁

        User user = new User();
        //spring中有一个对象之间拷贝
        BeanUtils.copyProperties(userRegisterForm, user);//源对象,拷贝到哪里的对象
        return userService.register(user);
    }
    @PostMapping("/user/login")
    public ResponseVo<User> login(@Valid @RequestBody UserLoginForm userLoginForm,
                                //  BindingResult bindingResult,
                                  HttpSession session
                                    ){//这里登录绑定session
    /*public ResponseVo<User> login(@Valid @RequestBody UserLoginForm userLoginForm,
                                  BindingResult bindingResult,
                                  HttpServletRequest httpServletRequest
                                    ){//这里登录绑定session*/
       /* if(bindingResult.hasErrors()){  //在购物车那一节删掉的
            return ResponseVo.error(PASSWORD_ERROR,bindingResult);
        }*/
        ResponseVo<User> userResponseVo = userService.login(userLoginForm.getUsername(),
                userLoginForm.getPassword());

        //设置session
       // HttpSession session = httpServletRequest.getSession();
        session.setAttribute(CURRENT_USER,userResponseVo.getData());

        /*userResponseVo.getData()=User(id=27, username=admina, password=,
         email=admina@qq.com, phone=null, question=null, answer=null, role=1,
         createTime=Fri Mar 17 11:19:44 CST 2023, updateTime=Fri Mar 17 11:19:44 CST 2023)*/

        log.info("/Login userResponseVo.getData()={}",userResponseVo.getData());

        log.info("/Login sessionId={}",session.getId());

        return userResponseVo;
/**
 * Cookie: JSESSIONID=3F921272F97F2A3A2A9208AEFA01C4DB
 * JSESSIONID=DD12BB9A990D9233CCE4EFD59FF17833
 */
    }
    //session保存在内存中，就很容易丢失,那就改进：token + redis  //分布式session,这里没讲
    @GetMapping("/user")
    public ResponseVo<User> userInfo(HttpSession session){
        log.info("/Login sessionId={}",session.getId());
        User user = (User)session.getAttribute(CURRENT_USER);
        /*if(user ==null){
            return ResponseVo.error(NEED_LOGIN);
        }*/
        return ResponseVo.success(user);
    }
    //todo 判断登录状态 拦截器
//退出登录

    /**
     * {@link org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory} 387行 getSessionTimeoutInMinutes
     * @param session
     * @return
     */
    //登出账号
    @PostMapping("/user/logout")
    public ResponseVo logout(HttpSession session){
        log.info("/user/logout sessionId={}",session.getId());

       /* User user = (User)session.getAttribute(CURRENT_USER);
        if(user ==null){
            return ResponseVo.error(NEED_LOGIN);
        }*/
        session.removeAttribute(CURRENT_USER);
        return ResponseVo.success();
    }
}





